import { store as stronge } from '../utils/utils';

/**
 * 整理搜索图书的原始请求
 */
export const regulateBookSearchResult = () => next => action => {
    if( action.type === 'BY_KEYWORD' || action.type === 'BY_NEXT_PAGE' ){
        let
        res = action.searchResult,
        curyear = new Date( res.timestamp * 1000 ).getUTCFullYear();

        res.books = res.books.map(function( e ){
                return {
                    allNum: e.allNum,
                    on: e.on,
                    searchId: e.searchId,
                    author: e.author.replace(/,$/, ''),
                    detail: e.detail,
                    isbn: e.isbn ? e.isbn.replace(/(-|\n)/g, '') : 'noimg.png',
                    press: e.press,
                    title: e.title,
                    year: e.year * 1 > curyear ? curyear : e.year
                }
            });

    }
    return next( action );
}

/**
 * 退出时清除本地数据
 */
export const logOut = () => next => action => {
    if( action.type === 'LOGOUT' ){
        stronge.clear();
    }
    return next( action );
}

/**
 * 展开Aside时判断当前的书是否在订阅列表中
 */
export const isLike = store => next => action => {
    if( action.type === 'SHOW_ASIDE' ){
        let subscibe = store.getState().USER.getIn( [ 'render', 'subscibe' ] ).toJS();
        action.isLike = subscibe.some( b => b.ctrlid === action.book.detail );
    }
    return next( action )
}
